<script setup lang="ts">
import loginApi from '@/api/sys/LoginApi.ts'
import {reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import type LoginReq from "@/type/LoginReq.ts";
import {useUserStore} from "@/pinia/useUser.ts";
import type FormItem from "@/components/form/type/FormItem.ts";

let userStore = useUserStore()
let route = useRoute()
let router = useRouter()
const loading = ref(false)

//登录表单的字段
const loginFormStructure: FormItem[] = [
  {row: 0, span: 24, key: "username", label: "用户名", type: "input", placeholder: "请输入用户名", attr: {autocomplete: "username", name: "username"}},
  {row: 1, span: 24, key: "password", label: "密　码", type: "password", placeholder: "请输入密码", attr: {autocomplete: "current-password", name: "current-password"}},
  {row: 2, span: 24, key: "operate", label: "操作", type: "slot"},
]
//登录表单绑定的数据
const loginReqModel = reactive<LoginReq>({
  username: '',
  password: ''
})

//登录
const doLogin = () => {
  loading.value = true
  loginApi.doLogin(loginReqModel).then(resp => {
    userStore.id = resp.id
    userStore.userName = resp.userName
    userStore.realName = resp.realName
    userStore.avatar = resp.avatar
    userStore.phone = resp.phone
    userStore.email = resp.email
    userStore.remark = resp.remark
    userStore.roles = resp.roles
    userStore.updatePermission(resp.permissions)

    //登录成功，跳转
    router.replace((route.query.redirect ?? "/") as string)
  }).finally(() => {
    loading.value = false
  })
}

</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <h1 class="login-title">欢迎登录</h1>
      <t-form :schema="loginFormStructure" v-model="loginReqModel">
        <template #operate="{field, model}">
          <div class="login-operate">
            <t-btn type="primary" html-type="submit" :loading="loading" @click="doLogin">登录</t-btn>
            <t-btn type="success" @click="console.log(model)">注册</t-btn>
          </div>
        </template>
      </t-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(145deg, #f0f4f8, #ffffff);
}

.login-card {
  position: relative;
  top: 25%;
  margin: 0 auto;

  width: 450px;
  background-color: #FFF;
  border-radius: 16px;
  padding: 40px 32px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #1f2d3d;
  margin-bottom: 16px;
}

.login-operate {
  display: flex;
  justify-content: center;
  margin-top: 12px;
  gap: 16px;
}

.login-operate Tb {
  flex: 1;
}
</style>